#include "stdafx.h"
#include "LiveServer.h"


CLiveServer *pLiveServer[CHANNEL][CONNECTCOUNT]={{NULL}};//

CLiveServer::CLiveServer(void)
{
	//OS_tskMutexCreate(&Mutex_GetVData);
	pVDataBuf=(BYTE *)malloc(MAXBUFSIZE);//2M
	memset(pVDataBuf,0,MAXBUFSIZE);
	p_Pos = 0;
    u_Pos = 0; 
	id = 0;
}

CLiveServer::~CLiveServer(void)
{
	free(pVDataBuf);
}

int CLiveServer::PushVData(BYTE *buf,Uint32 len)
{
	//printf("enter PushVData!\n");
	if((p_Pos+len)>MAXBUFSIZE)
	{
		//printf("p_Pos:%d,len:%d,MAXBUFSIZE-p_Pos:%d\n",p_Pos,len,MAXBUFSIZE-p_Pos);
		memcpy(pVDataBuf+p_Pos,buf,MAXBUFSIZE-p_Pos);
		//printf("MAXBUFSIZE-p_Pos:%d p_Pos+len-MAXBUFSIZE:%d\n",MAXBUFSIZE-p_Pos,p_Pos+len-MAXBUFSIZE);
		memcpy(pVDataBuf,buf+(MAXBUFSIZE-p_Pos),p_Pos+len-MAXBUFSIZE);
		
		p_Pos+=len;
		p_Pos%=MAXBUFSIZE;
		//printf("(p_Pos+len)>MAXBUFSIZE p_Pos:%d\n",p_Pos);
	}
	else
	{
		memcpy(pVDataBuf+p_Pos,buf,len);
		p_Pos+=len;
		p_Pos%=MAXBUFSIZE;
		//printf("p_Pos:%d\n",p_Pos);
	}
	//printf("leave PushVData!\n");
	return len;
}

Uint32 CLiveServer::GetVDataSize()
{
	if(p_Pos>=u_Pos)
	{
		return (p_Pos-u_Pos);
	}
	else
	{
		return (p_Pos+MAXBUFSIZE-u_Pos);
	}
}

int CLiveServer::GetVData(BYTE *buf,Uint32 len)
{
	//printf("enter GetVData!\n");
	if(p_Pos>u_Pos)
	{
		//printf("*****************p_Pos>u_Pos\n");
		if( (p_Pos-u_Pos)>=len )
		{
			//printf("u_Pos:%d len:%d\n",u_Pos,len);
			memcpy(buf,pVDataBuf+u_Pos,len);
			u_Pos+=len;
			//printf(">= p_Pos-u_Pos:%d\n",p_Pos-u_Pos);
		}
		else
		{
			//printf("< p_Pos-u_Pos:%d\n",p_Pos-u_Pos);
			return (p_Pos-u_Pos);
		}
	}
	else
	{
		//printf("*****************p_Pos<=u_Pos\n");
		if( (MAXBUFSIZE-u_Pos)>=len )
		{
			//printf("MAXBUFSIZE-u_Pos u_Pos:%d len:%d\n",len);
			memcpy(buf,pVDataBuf+u_Pos,len);
			//memcpy(buf+(MAXBUFSIZE-u_Pos),pVDataBuf,u_Pos+len-MAXBUFSIZE);
			u_Pos+=len;
			u_Pos%=MAXBUFSIZE;
			//printf(">= p_Pos+MAXBUFSIZE-u_Pos:%d\n",p_Pos+MAXBUFSIZE-u_Pos);
		}
		else
		{
			if(p_Pos+MAXBUFSIZE-u_Pos)
			{
				//printf("p_Pos+MAXBUFSIZE-u_Pos u_Pos:%d MAXBUFSIZE-u_Pos:%d\n",u_Pos,MAXBUFSIZE-u_Pos);
				memcpy(buf,pVDataBuf+u_Pos,MAXBUFSIZE-u_Pos);
				memcpy(buf+(MAXBUFSIZE-u_Pos),pVDataBuf,u_Pos+len-MAXBUFSIZE);
				u_Pos+=len;
				u_Pos%=MAXBUFSIZE;
			}
			else
			{
				//printf("< p_Pos+MAXBUFSIZE-u_Pos:%d\n",p_Pos+MAXBUFSIZE-u_Pos);
				return (p_Pos+MAXBUFSIZE-u_Pos);
			}
			
		}
	}
	//printf("leave GetVData!\n");
	return len;
}